Flash Article

Flash MX Professional 2004 Data Integration Using Microsoft Active Server Pages (ASP)

Phil Heinz

www.kalalau.org

For application developers who are serving dynamic data to users, the data integration cycle is an ever-present and critical hurdle, regardless of the programming language. How do you get the data from the database to the user, let the user change the data, and then save those changes back to the database? Mastering this cycle is critical. Successful applications depend on you being able to implement this cycle over and over again quickly and easily.

Macromedia Flash MX Professional 2004 represents a giant leap forward in mastering this cycle for Rich Internet Applications. This article will demonstrate how Flash MX Professional 2004 automates this cycle to let you get on with the business of application building and not get bogged down in the details. Specifically, I will discuss the Flash data bindings, packet communications from Flash to the server, and, more importantly, the middleware steps necessary to process the packets and update the database.

This article deconstructs a post made to the Flash Data Integration forum in November 2003. The middleware used is Microsoft Active Server Pages (ASP) and the database is Microsoft Access. However, you can apply the methods used to any middleware such as Macromedia ColdFusion, Microsoft ASP.NET, PERL, and to most databases available in the Microsoft Windows environment like Microsoft SQL Server, mySQL, and so on.

Requirements

To complete this tutorial you will need to install the following software and files:

Flash MX Professional 2004

Web server

A web server with IIS installed is required if you wish to run the application in this article. You must configure IIS to allow the execution of ASP Script files and writing to the Access file. If your web directory is not configured for writing, move the MDB file to a writable directory and change the ASP MapPath statement to reflect its new location.

Tutorials and sample files:

This ZIP archive contains Flash and ASP source files and a small Access database. See the readme.txt file in zip for installation instructions.

Note: You do not need Microsoft Access installed to run this example.

Application Overview

Figure 1 shows the outline of this tutorial's example application. It is a sample contacts database containing names, e-mail addresses, and phone numbers. (I bet you've never seen one of those!) The contacts database is an example of the data integration cycle using one table of data. The application starts when the user loads the Flash movie in his or her browser. The first thing that happens is that the Contacts_xmlcon instance of the XMLConnector component will trigger, calling ASP and getting the initial table of contacts in return. This component passes the returned array of contacts to a DataSet component, which sends it to a DataGrid and other Flash UI components. The DataSet immediately reflects any changes the user makes to the data through the UI components, because the DataSet and UI components are data-bound together.

Application overview

Figure 1. Application overview

As the user changes data, the Contacts_ds DataSet component tracks the changes, including added, modified, or deleted records. When you, as the programmer, are ready to save the changes for the user, simply call the applyUpdates() method on the DataSet. The DataSet then generates a delta packet, which describes the latest changes and sends them to an RDBMSResolver component, called Contacts_rs. The Resolver converts that data into an update packet and sends it to a second XMLConnector called SaveContacts_xmlcon. This XMLConnector then sends the update packet to ASP and waits for a response.

ASP executes all the transactions in the update packet against the database and sends a results packet back to Flash. The results packet confirms the success of all the transactions that the update packet sent. If any newly inserted records have autonumber or identity fields (depending on your database system), the results packet records these id values as well.

After creating the results packet, ASP sends it back to SaveContacts_xmlcon, which passes it back to the Contacts_rs RDBMSResolver. Contacts_rs passes it back to the DataSet as a delta packet. The DataSet then updates any new records with their new id values from the database and resets its own tracking data to start recording any new changes.

Remember, all this happened in Flash with two lines of ActionScript—the initial Contacts_xmlcon trigger and the applyUpdates() call to the DataSet. In the next section, I will cover the Flash data bindings in more detail before moving into ASP.

Flash Data Binding Path

Figure 2 shows the detailed Flash data-binding scheme of the initial incoming table of contacts. If you need instructions on how to apply the data bindings, Mark Rausch does a great job of step-by-step data binding and explaining the update and results Packets in his article, Using the RDBMSResolver to Update a Database with Macromedia Flash Professional 2004.

Open RDBMS-ASP2.fla. On the Content screen, there is an XMLConnector component named Contacts_xmlcon. The program triggers this component when it first starts. Since the Contacts_xmlcon results.contacts property is bound out to the Contacts_ds dataProvider, Contacts_xmlcon automatically sends the table of data returned from ASP to Contacts_ds.

Flash bindings for initial call to ASP

Figure 2. Flash bindings for initial call to ASP

This is the only time this application triggers Contacts_xmlcon. SaveContacts_xmlcon does all of the following communications with the database; SaveContacts_xmlcon sends only the changes and receives results. In the real world, with thousands of records, you may choose to operate the application differently.

For example, your Contacts_xmlcon could retrieve a subset of the data, avoiding a large initial download. SaveContacts_xmlcon would then save the changes on that data subset, then you could trigger Contacts_xmlcon again for another subset of data to work on.

When the Contacts_ds DataSet component has completed loading from Contacts_xmlcon, it will execute its dataProvider bindings to the Contacts_grd DataGrid component. The selectedIndex property of Contacts_grd is bound in/out with the Contacts_ds selectedIndex property so that any row selected by the user in the DataGrid will change the pointer in the DataSet to the corresponding record.

The name_txt, email_txt, and phone_txt TextInput components are bound in/out to the corresponding Contacts_ds fields. When a user selects a record in the Contacts_grd DataGrid, the appropriate record's data in Contacts_ds appears in the text boxes for her to edit. You could, alternatively, get rid of the TextInput components and just use the DataGrid to edit the data. Either way works fine. However, I have set the editable property of the DataGrid to false in this example.

Note that all the features you just coded only populate the application with its the initial data; they don't provide for user interaction and data manipulation. Everything you've built up to this point serves its purpose before the user ever interacts with the program! Once the data appears in Contacts_grd, the user can then manipulate the data, using the DataGrid to point to the desired record and the TextInput components to modify the data. As the text fields lose focus when they are changed or edited, you will see the DataGrid update immediately. This indicates that the Contacts_ds DataSet component has updated, because the text fields are only bound to the Contacts_grd indirectly through Contacts_ds.

Figure 3 shows the detailed Flash data-binding scheme for the database save/update cycles. This half of the Flash equation keeps the server and Flash synchronized. This is also the half that made my job much easier. This solved my issues with database updating that I'd experienced when doing this manually in previous versions of Flash.

Flash data binding scheme for database save/update cycles

Figure 3: Flash data binding scheme for database save/update cycles

Assume that you have loaded the data and the user has made some changes to it. When you are ready to save the changes, simply execute the applyUpdates() method of Contacts_ds. In this example, you can press the Save Changes to Database button. The rest is automatic data binding! Here's how it works.

When you execute applyUpdates(), Contacts_ds sends its delta packet, the collection of changes to the data, to Contacts_rs, an RDBMSResolver component. Contacts_rs converts the delta packet into an update packet and sends it to the SaveContacts_xmlcon XMLConnector component. In the example, I have set the kind property of SaveContacts_xmlcon's updatePacket param to AutoTrigger, which causes SaveContacts_xmlcon to automatically trigger an ASP call as soon as the update packet arrives. To see this setting, select the SaveContacts_xmlcon on the Stage, and click the Schema tab in the Component Inspector panel. Select the updatepacket param, you'll find the kind property in the panel below. Macromedia added this AutoTrigger kind to Flash MX 2004 with the 7.0.1 updater. If you don't have it installed, download the 7.0.1 updater now.

When SaveContacts_xmlcon receives a response from ASP, the response contains a results packet that contains the results of all transactions processed from the update packet it received. SaveContacts_xmlcon sends this results packet back to the Contacts_rs through its updateResults property. The Resolver passes the update packet back to the Contacts_ds DataSet as a delta packet.

Contacts_ds then reconciles the delta packet received against the delta packet it previously sent. The DataSet removes all the successfully completed transactions from the delta packet so they don't get sent again. Also, it updates any autonumber or identity fields with their new id values assigned by the database.

The results packet passes back to Flash any errors reported by the server database, like being unable to complete an insert or update for whatever reason. In RDBMS-ASP.as, you can see the code that shows any errors when the results show up at the DataSet:

DS = new Object();
DS.resolveDelta = function(eventObj) {
    var errs:Array = eventObj.data;
    for( var i:Number=0; i>errs.length; i++ ) {
        ShowMsg( errs[i].getMessage());
    }
}
Contacts_ds.addEventListener("resolveDelta",DS);

Because of the addEventListener function, DS.resolveDelta will execute when the DataSet completes the reconciliation process.

When you run the example and save changes to the database, you will see TextArea component labeled packets shows the update packet sent to ASP, and then shows the results packet received back from ASP. This happens rather quickly, so you may not get a good look at the update packet sent. If you change the kind property of SaveContacts_xmlcon.params.data.updatePacket to none, Flash will not send the update packet automatically. You then have time to examine the update packet in the packets window. You can easily copy it to your favorite editor and format it for reading if you like. Then, when you are ready to send the update packet to ASP, just press the Trigger SaveContacts_xmlcon button to continue the cycle.

To change the updatePacket kind property to none:

  1. Open the RDBMS-ASP.fla in Flash MX Professional 2004
  2. Click the Content form, then click the SaveContacts_xmlcon XMLconnector component on the Stage.
  3. In the Component Inspector Schema tab, click params.data.updatePacket.
  4. Set the kind property to none in the property list below the schema.

If you added any new records, you will see the contactid column of the new records update when the cycle completes. ASP has reported back to Contacts_ds the new autonumber values that Microsoft Access assigned when the records were added to the database.

ASP Sending the Initial Data for Flash

This article uses an ASP example called RDBMS-ASP.asp. A small subset of the code in this file starts the application by supplying to Flash all of the entries in the Contacts table of the RDBMS-ASP.mdb Access database. The process starts when Flash (Contacts_xmlcon to be exact) sends a request with a parameter called func. The func param in Flash is data-bound to a constant called GetContacts. You can see the following code executes in the ASP when it receives this request:

select case func
	case "GetContacts":
		rs1.Open "select * from Contacts order by name",cnn
		  Do Until rs1.EOF
			set recElement = ResultsPacket.createElement("rec")
			for i = 0 to rs1.Fields.Count - 1
			  recElement.setAttribute rs1(i).name, rs1(i).value
			  ResultsPacket.lastChild.appendChild recElement
			next
			rs1.MoveNext
		  Loop
		  rs1.close
	case . . .
	.
	.
	end select
	

This code fills out the XML document for return to Flash to populate the Contacts_ds DataSet. This XML document is called ResultsPacket, but it is actually just an array of contacts going back to Flash. It is only when called by SaveContacts_xmlcon that ASP sends an actual results packet for the DataSet.

You can test your installation by putting the following URL in your Microsoft Internet Explorer browser address window and pressing Enter:

http://yourserver/yourexampledir/rdbms-asp.asp?test=1&func=GetContacts

The test=1 parameter tells the ASP that this call does not have an XML document of parameters so it gets the func parameter from the URL itself. If you get a blank screen in response, just append a space to the URL in the browser address window and press Enter. The XML response with all the contacts will appear; this is the data that the ASP document sends to Flash.

GetContacts is the only function you can test from the browser directly because the SaveContacts function requires the update packet to be in an XML post document—the way SaveContacts_xmlcon sends it. You could modify the ASP to get an update packet off the URL, but what's the point? Putting an XML document on the URL just to test the function from the browser is a bit of overkill (insanity, rather).

ASP Updating the Database with Changes

When ASP detects a call from SaveContacts_xmlcon, Flash is sending the update packet of database changes. The ASP code receives the XML parameters as follows:

if Request("test")="1" then
			XMLRequest = false
			func = Request("func")
		else
			XMLRequest = true
			Set docReceived = CreateObject("MSXML2.DOMDocument") 
			docReceived.async = False 
			docReceived.load Request 
			Set RequestRoot = docReceived.documentElement
			func =	RequestRoot.getElementsByTagName("func")(0).text
		end if

The else section executes when Flash calls the ASP since Flash sends no test variable. This code imports the XML request into the object RequestRoot and derives the func parameter that specifies which function to perform, a Get or a Save.

When it detects a Save, the process is simply: Loop through the changes in the update packet and execute them against the database. This ASP file performs updates first, then deletes, and finally inserts.

Here is an example of an update packet containing only one record update:

<update_packet tableName="Contacts" nullValue="{_NULL_}" transID="IID74189225305:Fri Jan 23 09:37:01 GMT-0800 2004">
        <update id="IID65996659826">
          <field name="phone" type="String" oldValue="999-9999xxxx" newValue="999-9999x1234" key="false" />
          <field name="contactid" type="Integer" oldValue="116" key="true" />
          <field name="email" type="String" oldValue="t@h.com" newValue="t@h.net" key="false" />
          <field name="name" type="String" oldValue="Ted" newValue="Teddy" key="false" />
        </update>
</update_packet>

There is a list of fields to be updated under each update node in the update packet. One of those fields is the key field that identifies the record ID to be updated; the rest are simply the fields and values to be updated. There is no guarantee what order the fields are in, so the code must loop through them to find the key field itself. Once it has the key field, it loops through the rest of the fields again and builds the SQL update statements for execution.

Here is the ASP code that processes the update nodes:

'PROCESS ALL "UPDATE" NODES
Set UpdateNodes = UP.getElementsByTagName("update")
For Each UpdateNode In UpdateNodes
	'CREATE OPERATION RESULT NODE
		Set OpElement = ResultsPacket.createElement("operation")
		OpElement.SetAttribute "op","update"
		OpElement.SetAttribute "id",UpdateNode.getAttribute("id")

	Set UpdateFields = UpdateNode.getElementsByTagName("field")
	'Must iterate through fields once to get the key id -
	' No guarantee what order fields are in (key field not always the first one)
	For each UpdateField in UpdateFields
		If UpdateField.getAttribute("key") = "true" Then
			KeyField = UpdateField.getAttribute("name")
			KeyID = UpdateField.getAttribute("oldValue")
			Exit For
		End If
	Next
	
	'Check to see if id field exists, abort ADO call if it doesn't
	Dim SendCall
	If DBRETURNSERROR then
		SendCall = True
	Else
		If IDExists(Table,KeyField,KeyID) Then 
			SendCall = True
		Else
			OpElement.setAttribute "msg",KeyField & " " & KeyID & " does not exist"
			SendCall = False
		End If
	End If
	
	'Second time through For all non-key fields (fields to be updated)
	If SendCall then
		For each UpdateField in UpdateFields
			If UpdateField.getAttribute("key") = "false" Then
				fieldname = UpdateField.getAttribute("name")
				fieldtype = UpdateField.getAttribute("type")
				newfieldvalue = UpdateField.getAttribute("newValue")
				If fieldtype <> "Integer" and fieldtype <> "Number" Then
					newfieldvalue = "'" & newfieldvalue & "'"
				End If
				sql = "update " & Table & " Set " & fieldname & "=" & newfieldvalue & " where " & KeyField & "=" & KeyID
				On Error Resume Next
				cnn.Execute sql
				If cnn.Errors.Count > 0  Then
					OpElement.SetAttribute "msg",cnn.Errors(0).Description & "/" & sql
					cnn.Errors.Clear
				End If
				On Error Goto 0
			End If
		Next
	End If

	'Add Result Element to ResultsPacket
	ResultsPacket.lastChild.appendChild OpElement
Next

For a fun (depending on your point of view) advanced project, you could rewrite this segment with one loop instead of two—but who's counting! You could also create the entire SQL statement and execute it just once instead of making a call for each field as I do for this example. This works fine for this illustration, however, so I'll press on.

The last issue in updates is whether or not the database returns an error if the specified key value is not found in the database. Microsoft Access does not report these errors, so you make an initial call to the table before the update just to ensure a record with that key value exists. If it doesn't, then the logic reports an error for that transaction back to Flash. I'll cover the results packet more in the next section.

Here is an example of an update packet containing a delete and an insert:

<update_packet tableName="Contacts" nullValue="{_NULL_}" transID="IID23522107070:Fri Jan 23 09:43:52 GMT-0800 2004">
        <delete id="IID19942423282">
          <field name="contactid" type="Integer" oldValue="96" key="true" />
        </delete>
        <insert id="IID35544820130">
          <field name="contactid" type="Integer" newValue="" key="true" />
          <field name="phone" type="String" newValue="123-456-7890" key="false" />
          <field name="email" type="String" newValue="john@xyz.net" key="false" />
          <field name="name" type="String" newValue="John" key="false" />
        </insert>
</update_packet>

To request deletes, the update packet contains a list of fields under each delete node. Usually there is only one, and it represents the key field. But, just in case, the code loops through and picks out the key. That's all it needs to need to know about the record in question to make the delete SQL call.

Here is the ASP code that processes the delete nodes of the update packet:

'PROCESS ALL "DELETE" NODES
Set DeleteNodes = UP.getElementsByTagName("delete")
For Each DeleteNode In DeleteNodes
	'CREATE OPERATION RESULT NODE
		Set OpElement = ResultsPacket.createElement("operation")
		OpElement.SetAttribute "op","delete"
		OpElement.SetAttribute "id",DeleteNode.getAttribute("id")

	'FIND KEY FIELD SO WE CAN BUILD SQL STMT
	Set DeleteFields = DeleteNode.getElementsByTagName("field")
	For each DeleteField in DeleteFields
		If DeleteField.getAttribute("key") = "true" Then
			KeyField = DeleteField.getAttribute("name")
			KeyID = DeleteField.getAttribute("oldValue")
			Exit For
		End If
	Next
	
	'Microsoft Access doesn't report an error when a delete is called for a keyvalue that 
	'doesn't exist, but since it's already gone from our Flash dataset, we'll just let it
	'think that it worked. Other types of errors will still be reported, and dbs that do return
	'errors are handled fine.
	
	'Delete from DB
		sql = "delete from " & Table & " where " & KeyField & "=" & KeyID
		On Error Resume Next
		cnn.Execute sql
		If cnn.Errors.Count > 0 Then
			OpElement.SetAttribute "msg",cnn.Errors(0).Description & "/" & sql
			cnn.Errors.Clear
		End If
		On Error Goto 0

	'Add Result Element to ResultsPacket
		ResultsPacket.lastChild.appendChild OpElement
Next

Databases like Access do not return an error if you try to delete a record that does not exist. When this happens, since the goal was to remove the record anyway, the code reports the transaction as complete and lets Flash go on its happy way knowing its delete worked. (I won't tell if you won't!) You could easily program any other logic for handling similar situations on your database of choice.

To handle inserts, there is also a list of fields under each insert node in the update packet. In the ASP, you can see how the code loops through the fields, building the insert statement as it goes. At the end, it calls the database. (And you and I hope for the best.)

Here is the ASP code for processing the insert nodes from the update packet:

'PROCESS ALL "INSERT" NODES
Set InsertNodes = UP.getElementsByTagName("insert")
For Each InsertNode In InsertNodes
	'CREATE OPERATION RESULT NODE
		Set OpElement = ResultsPacket.createElement("operation")
		OpElement.SetAttribute "op","insert"
		OpElement.SetAttribute "id",InsertNode.getAttribute("id")

	'Gather fields to build SQL stmt
	Set InsertFields = InsertNode.getElementsByTagName("field")
	FieldsStr = ""
	ValuesStr = ""
	For each InsertField in InsertFields
		fieldname = InsertField.getAttribute("name")
		fieldtype = InsertField.getAttribute("type")
		If InsertField.getAttribute("key") = "false" Then
			'NON-KEY FIELD, INCLUDE IN INSERT STMT
			newfieldvalue = InsertField.getAttribute("newValue")
			If fieldtype = "Integer" or fieldtype = "Number" Then
				ValStr = newfieldvalue
			Else
				ValStr = "'" & newfieldvalue & "'"
			End If
			If len(ValuesStr) > 0 Then
				ValuesStr = ValuesStr & "," & ValStr
			Else
				ValuesStr = ValStr
			End If
			If len(FieldsStr) > 0 Then
				FieldsStr = FieldsStr & "," & InsertField.getAttribute("name")
			Else
				FieldsStr = InsertField.getAttribute("name")
			End If
		Else
			'KEY FIELD
			KeyField = fieldname
		End If
	Next

	'INSERT TO DB
		Identity = ""
		If DBRETURNSIDENTITY Then
			On Error Resume Next
			rs1.Open sql,cnn
			If cnn.Errors.Count > 0 Then
				OpElement.SetAttribute "msg",cnn.Errors(0).Description & "/" & sql
				cnn.Errors.Clear
			End If
			If rs1.State = adStateOpen Then
				rs1.Close
			End If
		Else
			'These statements will work with Microsoft Access - unfortunately, you can't return the identity value
			'so you have to do a quick select statement - could cause data collisions in multi-user environment
			sql = "insert into " & Table & " (" & FieldsStr & ") values(" & ValuesStr & ")"
			On Error Resume Next
			cnn.Execute sql
			If cnn.Errors.Count > 0 Then
				OpElement.SetAttribute "msg",cnn.Errors(0).Description & "/" & sql
				cnn.Errors.Clear
			Else
			End If
		End If
		
		On Error Goto 0

	'IDENTIFY NEW KEY VALUE FOR THIS NEW RECORD
		If Not DBRETURNSIDENTITY Then
			'FOR ACCESS, GET LAST KEYFIELD IN DB - NOT GOOD FOR MULTIUSER ENVIRONMENT, ALL WE CAN DO FOR NOW
				rs1.open "select top 1 " & KeyField & " from " & Table & " order by " & KeyField & " desc",cnn
				Identity = rs1(KeyField)
				rs1.close
		End If

		If Len(Identity) > 0 Then
			'PUT IDENTITY IN FIELD NODE
			Set IDElement = ResultsPacket.createElement("field")
			IDElement.SetAttribute "name",KeyField
			IDElement.SetAttribute "curValue",Identity
			OpElement.appendChild IDElement
		End If

	'Add Result Element to ResultsPacket
		ResultsPacket.lastChild.appendChild OpElement
Next

Microsoft Access does not return an ID value for autonumber fields like the "big boys" do. You have to make a quick call for the latest ID value from the table so you notify Flash with the ID value for the new record you inserted. This leaves the potential for conflicts in multiuser systems, since other records could be added before your "quick call" executes, returning the wrong ID field. I'll stick with this approach because, while not foolproof, it's easy.

You can see in the ASP file comments that, with just a few changes, you can have this ASP ready for Microsoft SQL Server, which does report back an identity value at the end of an insert call. This would remove the above-mentioned multiuser collision risk.

ASP Sending Results Back to Flash

Near the top of the ASP file, check out the code that creates the Results Packet XML document:

Set ResultsPacket = Server.Createobject("MSXML.DOMDocument")
Set dtd = ResultsPacket.createProcessingInstruction("xml", "version=" & dqt & "1.0" & dqt )
ResultsPacket.appendChild dtd
Set ResultsPacketElement = ResultsPacket.createElement("results_packet")
ResultsPacket.appendChild ResultsPacketElement

To build the results packet, you're simply filling out this XML document, appending one operation node for each insert, update, and delete node in the update packet. Also, as you examine the code in the ASP file, you can see that before you process the update nodes, you issue the following command to set the ID value of the results packet to the ID value of the update packet, so the DataSet in Flash can compare them correctly:

ResultsPacketElement.SetAttribute "transID",UP.getAttribute("transID")

UP is the document root of the update packet. From here on, you can see how to create a results packet operation node for every update packet node processed. Right below the start of the updates loop, you can see this code creating the result packet operation node corresponding to the current update transaction.

Set OpElement = ResultsPacket.createElement("operation")
OpElement.SetAttribute "op","update"
OpElement.SetAttribute "id",UpdateNode.getAttribute("id")

At the end of each node update, you add a msg attribute to the operation node if there was an error, letting the DataSet know that transaction failed. If there is no error, the OpElement node stays just as you made it above, telling Flash that the transaction was successful. You then append that operation node to the results packet, which is the last statement you see in each node type loop:

ResultsPacket.lastChild.appendChild OpElement

The delete and insert loops also create an operation node for each transaction. They work the same way as the updates I have just described.

With the insert loop, you place the value of the autonumber or identity field of the newly created record into a field node under that operation node. This lets the DataSet know what the new id field is for the record it sent. Here is an example of a results packet containing the results of three successful operations:

<results_packet transID="IID72839220893:Fri Jan 23 11:42:15 GMT-0800 2004">
        <operation op="update" id="IID4584106663" />
        <operation op="delete" id="IID30979323527" />
        <operation op="insert" id="IID85040367069">
          <field name="contactid" curValue="119" />
        </operation>
</results_packet>

At the end of the ASP execution, we have a results packet XML document containing operation nodes that tell the DataSet in Flash how the transactions went with the database. The ASP writes this results packet out with the following line:

Response.Write ResultsPacket.xml

Using Other Middleware and Databases

Connecting to another database can be accomplished simply by changing the connection string after the cnn.open command. You could use another direct driver like the Microsoft Jet driver you are using in this example, or you could use a standard ODBC connection string and connect to any ODBC source you have defined on your server.

To find a connection string for your database, simply Google "database connection strings," and you will be rewarded with hundreds of samples.

To get this ASP logic to work correctly, however, you must set the two constants correctly at the top of the ASP file. These constants define your database's capabilities so the script can adjust appropriately.

Constant Type Purpose
DBRETURNSERROR Boolean Lets the script know if the database returns an error on an Update when the key field is not found
DBRETURNSIDENTITY Boolean Indicates whether the database returns the new identity or autonumber key value after an insert

If you lay your offerings at the feet of other middleware like Macromedia ColdFusion, ASP.NET, or PERL, do not fear. The general principles used in this example are applicable to any other middleware. As long as it can receive a POST XML document, iterate through it, connect to the database, and return an XML document, it will work. All of the above-mentioned middleware, and most others, will work just fine. Depending on the middleware you choose, you may have to use the WebServicesConnector component instead of the XMLConnector component in Flash, but you can produce the same results. Check this out in Ben Forta's article, Employee Updater: Building a Client-Server Application with Macromedia Flash Data Connection Wizard and ColdFusion.

Summary

Using Flash MX Professional 2004 data components with middleware that understands and supports them, you can quickly and easily create screen after screen of dynamic data, arranged in any way that users need it served up. That is, after all, what it's all about, right?

For a more in-depth look at the overall data integration strategy of Flash MX Professional 2004, see the Macromedia Flash Data Integration Overview:

Macromedia Flash Data Integration Overview (Flash Developer Center)

There are other great sample applications and articles in the Macromedia Development Center as well, including the aforementioned superb article by Mark Rausch:

Using the RDBMSResolver to Update a Database with Flash MX Professional 2004

Also, Leo Schuman wrote a great article on the XMLConnector component and binding/formatting the UI:

Bike Trips Sample Application: Using the XMLConnector Component in Flash MX Professional 2004

Happy application building!


About the author

Phil Heinz has been a computer nerd since high school. During the 20 years since, he has developed applications for NASA, the United States Navy, Fortune 1000 companies and state and federal governments around the world. For the last five years, he has been integrating Flash into manufacturing processes. Phil and his wife Michelle own Kalalau Enterprises (www.kalalau.org) in Citrus Heights, CA. You can reach Phil by email at pilipo@kalalau.org.